var LoginForm = function () {
  var template = /* html */ `
    <div class="login-form" v-loading.fullscreen.lock="loading">
      <div class="login-form-tabs">
        <div :class="{select:loginType==='code'}" @click="changeTab('code')">扫码登录</div>
        <div :class="{select:loginType==='account'}" @click="changeTab('account')">账号登录</div>
      </div>
      <div class="login-form-content">
        <template v-if="loginType==='account'">
          <el-form ref="loginForm" :model="loginUser" label-width="calc(4em + 12px)">
            <el-form-item label="公司名称" prop="company">
              <el-input v-model="loginUser.company" :disabled="checkCodeLoading" placeholder="请输入公司名称" @change="setCodeBtn">
              </el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="loginUser.userName" placeholder="请输入用户名/手机号"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="loginUser.password" type="password" placeholder="请输入密码" autocomplete="new-password"></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="verificationCode">
              <template v-if="canCheckCode">
                <el-input style="width:calc(100% - 116px)" v-model="loginUser.verificationCode" placeholder="请输入验证码">
                </el-input>
                <countdown-button ref="countdownBtn" text="获取验证码" actionText="重新获取" width="112px" type="primary" :count="60" :before-click-fun="getVerificationCode">
                </countdown-button>
              </template>
              <span v-else>无需验证码</span>
            </el-form-item>
          </el-form>
          <div style="text-align:center">
            <el-button :disabled="checkCodeLoading" type="primary" @click="toLogin">登录</el-button>
            <el-button type="primary" @click="resetForm">重置</el-button>
          </div>
        </template>
        <div v-else-if="loginType==='code'">
          <div id="login-code"></div>
        </div>
      </div>
    </div>
  `;

  return {
    data: function () {
      var loginUser = this.getLoinUser();
      return {
        loading: false,
        btnLoading: false,
        checkCodeLoading: false,
        canCheckCode: false,
        loginType: 'code',
        loginUser: loginUser
      };
    },

    watch: {
      canCheckCode: function (val) {
        if (!val) {
          this.loginUser.verificationCode = '';
        }
      },

      loginType: {
        immediate: true,
        handler: function () {
          if (this.loginType === 'code') {
            var hostname = window.location.hostname;
            var state;
            switch (hostname) {
              case '8888.shinehao.net':
                state = 5;
                break;
              case 'www.shinehao.net':
                state = 6;
                break;
              case 'www.shinehao.com.cn':
                state = 7;
                break;
              case 'www.aieyewear.com.cn':
                state = 8;
            }
            this.$nextTick(function () {
              new WxLogin({
                self_redirect: false,
                id: "login-code",
                appid: "wx3591eb8fae70db63",
                scope: "snsapi_login",
                redirect_uri: "https://www.shinehao.net/weixin/wxloginScanQrcode.html",
                state: state,
                style: "",
                href: ""
              });
            });
          }
        }
      }
    },

    created: function () {
      this.setCodeBtn();
    },

    methods: {
      changeTab: function (tabName) {
        var loginType = this.loginType;
        if (loginType === tabName) {
          return;
        }
        this.loginType = tabName;
      },

      getLoinUser: function () {
        var loginUser = {
          company: '',
          userName: '',
          password: '',
          verificationCode: ''
        };
        return loginUser;
      },

      setCodeBtn: function () {
        var company = this.loginUser.company;
        if (company === '') {
          this.canCheckCode = false;
          return;
        }

        this.checkCodeLoading = true;
        var self = this;
        ajaxRequest('company/getCompanyByCompanyName', {
          company: company
        }).then(function (user) {
          self.checkCodeLoading = false;
          if (user === null) {
            self.canCheckCode = false;
            return;
          }

          var isNeedCode = user.isNeedCode;
          self.canCheckCode = isNeedCode !== 0;
        }).catch(function () {
          self.checkCodeLoading = false;
        });
      },

      getVerificationCode: function () {
        var code = this.checkValid();
        if (code !== '') {
          var msg = i18n.getMsg(`login.error.${code}`);
          this.$alert(msg, '信息')
          return Promise.reject();
        }

        var postData = _.cloneDeep(this.loginUser);
        delete postData.verificationCode;
        var self = this;
        return ajaxRequest('user/sendVerificationCode', postData).then(function (data) {
          var msg;
          if (data === 1) {
            msg = `
              <div class="code-error-div">
                <div class="code-error-text">此账号还没有关联微信，无法接收验证码，请扫码关联</div>
                <div class="code-error-img"><img src="./img/relation.png"></div>
              </div>
            `;
          } else if (data === 2) {
            msg = `
              <div class="code-error-div">
                <div class="code-error-text">此账号未关注公众号，无法接收验证码，请扫码关注</div>
                <div class="code-error-img"><img src="./img/public.jpg"></div>
              </div>
            `;
          }

          if (msg) {
            self.$alert(msg, '提示', {
              dangerouslyUseHTMLString: true
            });
            return false;
          }

          return true;
        }).catch(function () {
          return false;
        });
      },

      toLogin: function () {
        var canCheckCode = this.canCheckCode;
        var code = this.checkValid(canCheckCode);
        if (code !== '') {
          var msg = i18n.getMsg(`login.error.${code}`);
          this.$alert(msg, '信息')
          return;
        }

        var postData = _.cloneDeep(this.loginUser);
        if (!canCheckCode) {
          delete postData.verificationCode;
        }
        postData.autoLogin = 'autoLogin';

        this.loading = true;
        var self = this;
        ajaxRequest('user/loginByVerificationCode', postData).then(function (msg) {
          self.loading = false;
          self.$emit('login-success');
        }).catch(function () {
          self.loading = false;
        });
      },

      checkValid: function (hasCode) {
        var loginUser = this.loginUser;
        var fields = ['company', 'userName', 'password'];
        if (hasCode) {
          fields.push('verificationCode');
        }
        return CheckVaildUtil.checkNullField(fields, loginUser);
      },

      resetForm: function () {
        this.$refs['loginForm'].resetFields();
        this.canCheckCode = false;
      }
    },

    components: {
      CountdownButton: CountdownButton
    },

    template: template
  };
}();
